﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Utilities;
using Telerik.Web.UI;
using System.Drawing;
using Web;
using System.Data;
using Domain.DAL;
using Domain.Models;

namespace WebApp.ReportsAndStatistics
{
    public partial class GeneralReport : System.Web.UI.Page
    {
        #region Private Fields

        private string _preUrl = "~/ReportsAndStatistics/GeneralReport.aspx";
        private string _cookiesName = string.Empty;

        #endregion

        #region Private Properties

        public string ReportDateFrom
        {
            get
            {
                if (rdpReportDateFrom.SelectedDate.HasValue && rdpReportDateFrom.SelectedDate.Value != null)
                {
                    return rdpReportDateFrom.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpReportDateFrom.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpReportDateFrom.SelectedDate = null;
                }
            }
        }

        public string ReportDateTo
        {
            get
            {
                if (rdpReportDateTo.SelectedDate.HasValue && rdpReportDateTo.SelectedDate.Value != null)
                {
                    return rdpReportDateTo.SelectedDate.Value.ToString(MyConfig.DateFormat);
                }
                return string.Empty;
            }
            set
            {
                try
                {
                    rdpReportDateTo.SelectedDate = DateTime.ParseExact(value, MyConfig.DateFormat, null);
                }
                catch (Exception)
                {
                    rdpReportDateTo.SelectedDate = null;
                }
            }
        }

        #endregion 
       
        #region RadGrid's Event Handlers

        protected void grdResult_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
        {
            try
            {
                Utility.TranslateGridPagerItem(e);
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_ItemDataBound(object sender, GridItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == GridItemType.AlternatingItem || e.Item.ItemType == GridItemType.Item)
                {
                    GridEditableItem editableItem = (GridEditableItem)e.Item;
                    if (editableItem != null)
                    {
                        //Format color
                        string displayColor = editableItem["DisplayColor"].Text.Trim();
                        if (!string.IsNullOrEmpty(displayColor) && displayColor != "&nbsp;")
                        {
                            editableItem.BackColor = ColorTranslator.FromHtml(displayColor);
                        }

                        //Set navigate url for hyperlink fullname
                        string repairingTicketID = editableItem["RepairingTicketID"].Text.Trim();
                        if (!string.IsNullOrEmpty(repairingTicketID))
                        {
                            HyperLink hplFullName = (HyperLink)editableItem["FullName"].FindControl("hplFullName");
                            if (hplFullName != null)
                            {
                                hplFullName.NavigateUrl = this.ResolveUrl("~/RepairingTickets/TicketDetails.aspx") + "?RepairingTicketID=" + repairingTicketID + "&preUrl=" + this._preUrl;
                            }
                        }

                        //format cost
                        if (!string.IsNullOrEmpty(editableItem["Cost"].Text.Trim()) && editableItem["Cost"].Text.Trim() != "&nbsp;")
                        {
                            editableItem["Cost"].Text = Utility.FormatNumber(editableItem["Cost"].Text, MyConfig.CurrencyFormat, TypeCode.Decimal);
                        }

                        //Visible check warranty
                        string checkWarranty = editableItem["IsValidWarranty"].Text.Trim();
                        string visibleCheckWarranty = editableItem["VisibleCheckWarranty"].Text.Trim();

                        if (!string.IsNullOrEmpty(visibleCheckWarranty) && !string.IsNullOrWhiteSpace(visibleCheckWarranty))
                        {
                            System.Web.UI.WebControls.Image imgCheckWarranty = (System.Web.UI.WebControls.Image)editableItem["ColCheckWarranty"].FindControl("imgCheckWarranty");
                            if (imgCheckWarranty != null)
                            {
                                imgCheckWarranty.Visible = Convert.ToBoolean(visibleCheckWarranty);

                                if (imgCheckWarranty.Visible)
                                {
                                    if (!string.IsNullOrEmpty(checkWarranty) && !string.IsNullOrWhiteSpace(checkWarranty) && checkWarranty != "&nbsp;")
                                    {
                                        if (checkWarranty == "1")
                                        {
                                            imgCheckWarranty.ImageUrl = this.ResolveUrl("~/images/ValidWarranty.gif");
                                        }
                                        else
                                        {
                                            imgCheckWarranty.ImageUrl = this.ResolveUrl("~/images/InvalidWarranty.gif");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            try
            {
                BindGrid();
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_PageSizeChanged(object sender, GridPageSizeChangedEventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.PageSizeCookiesName, e.NewPageSize.ToString());
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void grdResult_PageIndexChanged(object sender, GridPageChangedEventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.CurrentPageIndexCookiesName, e.NewPageIndex.ToString());
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        #endregion

        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {

            try
            {
                (Master as ReportsAndStatisticsPages).SelectedTab = "reportsAndStatistics";
                _cookiesName = this.GetType().Name + Session.SessionID;
                if (!IsPostBack)
                {
                    LoadForm();
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnReport_Click(object sender, EventArgs e)
        {
            try
            {
                CookiesManager.Update(this._cookiesName, MyConfig.CurrentPageIndexCookiesName, "0");

                CookiesManager.Update(this._cookiesName, rcbProductType.ID, rcbProductType.SelectedValue);
                CookiesManager.Update(this._cookiesName, rcbRepairingType.ID, rcbRepairingType.SelectedValue);
                CookiesManager.Update(this._cookiesName, rcbRepairer.ID, rcbRepairer.SelectedValue);

                CookiesManager.Update(this._cookiesName, rdpReportDateFrom.ID, this.ReportDateFrom);
                CookiesManager.Update(this._cookiesName, rdpReportDateTo.ID, this.ReportDateTo);

                grdResult.Rebind();
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        #endregion

        #region Private Methods

        private void BindGrid()
        {
            try
            {
                DataSet ds = new DataSet();

                ReportsAndStatisticsDAO rsDAO = ReportsAndStatisticsDAO.GetInstance();
                if (rsDAO != null)
                {
                    string productTypeID = MyConfig.NullNumber.ToString();
                    if (!string.IsNullOrEmpty(rcbProductType.SelectedValue))
                    {
                        productTypeID = rcbProductType.SelectedValue;
                    }

                    string repairingTypeID = MyConfig.NullNumber.ToString();
                    if (!string.IsNullOrEmpty(rcbRepairingType.SelectedValue))
                    {
                        repairingTypeID = rcbRepairingType.SelectedValue;
                    }

                    string repairer = MyConfig.NullNumber.ToString();
                    if (!string.IsNullOrEmpty(rcbRepairer.SelectedValue))
                    {
                        repairer = rcbRepairer.SelectedValue;
                    }

                    ds = rsDAO.GeneralReport(productTypeID, repairingTypeID, repairer, ReportDateFrom, ReportDateTo);
                    if (ds != null && ds.Tables.Count > 1)
                    {
                        if (ds.Tables[ds.Tables.Count - 1].Rows.Count > 0)
                        {
                            if (ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalQuantity"] != null && ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalQuantity"] != DBNull.Value)
                            {
                                lblTotalQuantity.Text = Utility.FormatNumber(ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalQuantity"].ToString(), MyConfig.NumberFormat, TypeCode.Int64);
                            }
                            if (ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalCost"] != null && ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalCost"] != DBNull.Value)
                            {
                                lblTotalCost.Text = Utility.FormatNumber(ds.Tables[ds.Tables.Count - 1].Rows[0]["TotalCost"].ToString(), MyConfig.CurrencyFormat, TypeCode.Decimal);
                            }

                        }
                        grdResult.DataSource = ds.Tables[0];
                    }

                }

                //Get stored value from cookies
                if (CookiesManager.GetValue(this._cookiesName, MyConfig.PageSizeCookiesName) != null)
                {
                    grdResult.PageSize = Convert.ToInt32(CookiesManager.GetValue(this._cookiesName, MyConfig.PageSizeCookiesName));
                }
                if (CookiesManager.GetValue(this._cookiesName, MyConfig.CurrentPageIndexCookiesName) != null)
                {
                    grdResult.CurrentPageIndex = Convert.ToInt32(CookiesManager.GetValue(this._cookiesName, MyConfig.CurrentPageIndexCookiesName));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void LoadForm()
        {
            try
            {
                (Master as ReportsAndStatisticsPages).PageTitle = Resources.Strings.GeneralReport;

                BindProductTypes();
                BindRepairingTypes();
                BindRepairers();

                this.ReportDateTo = DateTime.Now.ToString(MyConfig.DateFormat);
                this.ReportDateFrom = DateTime.Now.AddDays(Convert.ToInt32(GetParameterValue(MyConfig.ReportDateAgoCode, "-30"))).ToString(MyConfig.DateFormat);


                //Get stored value from cookies
                if (CookiesManager.GetValue(this._cookiesName, rcbProductType.ID) != null)
                {
                    rcbProductType.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbProductType.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rdpReportDateFrom.ID) != null)
                {
                    this.ReportDateFrom = CookiesManager.GetValue(this._cookiesName, rdpReportDateFrom.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rdpReportDateTo.ID) != null)
                {
                    this.ReportDateTo = CookiesManager.GetValue(this._cookiesName, rdpReportDateTo.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbRepairingType.ID) != null)
                {
                    rcbRepairingType.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbRepairingType.ID);
                }
                if (CookiesManager.GetValue(this._cookiesName, rcbRepairer.ID) != null)
                {
                    rcbRepairer.SelectedValue = CookiesManager.GetValue(this._cookiesName, rcbRepairer.ID);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void BindRepairingTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                RepairingTypeDAO daoObject = RepairingTypeDAO.GetInstance();
                RepairingType rt = new RepairingType();

                ds = daoObject.Search(rt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbRepairingType, ds, "RepairingTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindProductTypes()
        {
            DataSet ds = new DataSet();
            try
            {
                ProductTypeDAO daoObject = ProductTypeDAO.GetInstance();
                ProductType pt = new ProductType();

                ds = daoObject.Search(pt);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbProductType, ds, "ProductTypeName", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindRepairers()
        {
            DataSet ds = new DataSet();
            try
            {
                EmployeeDAO daoObject = EmployeeDAO.GetInstance();
                Employee e = new Employee();

                ds = daoObject.Search(e);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbRepairer, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private string GetParameterValue(string code, string defaultValue)
        {
            string value = defaultValue;
            try
            {
                Domain.DAL.ParameterDAO pDAO = Domain.DAL.ParameterDAO.GetInstance();
                if (pDAO != null)
                {
                    Domain.Models.Parameter p = new Domain.Models.Parameter();

                    p = pDAO.GetByCode(code);
                    if (p != null && !string.IsNullOrEmpty(p.Value))
                    {
                        value = p.Value;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return value;
        }

        #endregion
    }
}